import Vue from 'vue'

// 设备类型断点定义
const breakpoints = {
  xs: 480,  // 超小屏幕
  sm: 768,  // 小屏幕（手机）
  md: 992,  // 中等屏幕（平板）
  lg: 1200  // 大屏幕（桌面）
}

// 创建响应式设备状态对象
const deviceState = Vue.observable({
  width: typeof window !== 'undefined' ? window.innerWidth : 0,
  height: typeof window !== 'undefined' ? window.innerHeight : 0,
  isMobile: false,
  isTablet: false,
  isDesktop: false,
  isSmallMobile: false,
  isLandscape: false,
  isPortrait: true
})

// 更新设备状态的函数
function updateDeviceState() {
  if (typeof window === 'undefined') return

  // 获取当前窗口尺寸
  const width = window.innerWidth
  const height = window.innerHeight
  
  // 更新设备状态
  deviceState.width = width
  deviceState.height = height
  
  // 判断设备类型
  deviceState.isMobile = width < breakpoints.sm
  deviceState.isTablet = width >= breakpoints.sm && width < breakpoints.lg
  deviceState.isDesktop = width >= breakpoints.lg
  deviceState.isSmallMobile = width < breakpoints.xs
  
  // 判断屏幕方向
  deviceState.isLandscape = width > height
  deviceState.isPortrait = width <= height
}

// 防抖函数
function debounce(fn, delay = 250) {
  let timer = null
  return function() {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, arguments)
    }, delay)
  }
}

// 创建Vue插件
const DevicePlugin = {
  install(Vue) {
    // 初始更新设备状态
    updateDeviceState()
    
    // 监听窗口尺寸变化，使用防抖优化性能
    if (typeof window !== 'undefined') {
      window.addEventListener('resize', debounce(updateDeviceState, 100))
    }
    
    // 将设备状态对象挂载到Vue原型上
    Vue.prototype.$device = deviceState
    
    // 提供工具方法来判断设备类型
    Vue.prototype.$isDevice = function(type) {
      switch (type) {
        case 'mobile': return deviceState.isMobile
        case 'tablet': return deviceState.isTablet
        case 'desktop': return deviceState.isDesktop
        case 'smallMobile': return deviceState.isSmallMobile
        case 'landscape': return deviceState.isLandscape
        case 'portrait': return deviceState.isPortrait
        default: return false
      }
    }
    
    // 添加全局mixin，使设备状态在所有组件中可用
    Vue.mixin({
      computed: {
        $deviceState() {
          return deviceState
        },
        isMobile() {
          return deviceState.isMobile
        },
        isTablet() {
          return deviceState.isTablet
        },
        isDesktop() {
          return deviceState.isDesktop
        },
        isSmallMobile() {
          return deviceState.isSmallMobile
        }
      }
    })
  }
}

export default DevicePlugin 